// 导入
const express = require("express");

const app = express();

const cors = require("cors");

const config = require("./config");

const { expressjwt: expressJWT } = require("express-jwt");
// 允许跨域
app.use(cors());

app.use(express.urlencoded({ extended: false }));

app.use(express.json());

app.use(function (req, res, next) {
  res.response = function (err, code = 1) {
    res.send({
      code,
      message: err instanceof Error ? err.message : err,
    });
  };
  next();
});

// 公开静态文件夹
app.use("/public/", express.static("./public"));


// 导入并使用路由
const admin = require("./routes/admin");
const user = require("./routes/user");
const category = require("./routes/category");
const pet = require("./routes/pet");
const record = require("./routes/record");
const carousel = require("./routes/carousel");
const knowledge = require("./routes/knowledge");
const post = require("./routes/post");
const post_comment = require("./routes/post_comment");
const upload = require("./routes/upload");
const count = require("./routes/count");
app.use("/api", admin, user, upload, category, pet, carousel, post, post_comment, knowledge, record, count);
app.use(function (err, req, res, next) {
  if (err.name === "UnauthorizedError")
    return res.response("认证失败", 401);
  res.response(err);
});

//  启动web服务器
app.listen(9001, function () {
  console.log("api server running at http://127.0.0.1:9001");
});
